package models

import (
	"fmt"
	"github.com/olivere/elastic/v7"
	"github.com/redis/go-redis/v9"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"log"
)

var DB *gorm.DB

// InitMysql todo 数据库连接（闭包函数）
func InitMysql(mysqlFunc func(DB *gorm.DB) error) error {
	var err error
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		MysqlConfig.Username, MysqlConfig.Password, MysqlConfig.Host, MysqlConfig.Port, MysqlConfig.Database,
	)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})
	if err != nil {
		panic(err)
	}
	log.Println(MysqlConfig, "////")
	log.Println("连接成功")
	err = mysqlFunc(DB)
	exit, _ := DB.DB()
	defer exit.Close()
	return err
}

// InitEs todo es连接（闭包函数）
func InitEs(esFunc func(*elastic.Client) (interface{}, error)) (interface{}, error) {
	dsn := fmt.Sprintf("http://%s:%d", EsConfig.Host, EsConfig.Port)
	Esclient, err := elastic.NewClient(elastic.SetURL(dsn), elastic.SetSniff(false))
	if err != nil {
		panic(err)
	}
	res, err := esFunc(Esclient)
	defer Esclient.Stop()
	return res, err
}

// InitRedis todo redis连接（闭包函数）
func InitRedis(redisFunc func(client *redis.Client) (interface{}, error)) (interface{}, error) {
	Redis := redis.NewClient(&redis.Options{
		Addr: fmt.Sprintf("%s:%d", RedisConfig.Host, RedisConfig.Port),
		DB:   RedisConfig.DB,
	})
	res, err := redisFunc(Redis)
	defer Redis.Close()
	return res, err
}
